package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Menu;
import com.itheima.health.service.MenuService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("menu")
public class MenuController {
    @DubboReference
    private MenuService menuService;

    /**
     * @Author: 位帅帅
     * @Date: 21:03 2021/1/12
     * @Params: []
     * @RerurnType: com.itheima.health.entity.Result
     * @Description: 查询所有菜单
    */
    @PreAuthorize("hasAuthority('MENU_QUERY')")
    @GetMapping("findAll")
    public Result findAll() {
        List<Menu> menuList = menuService.findAll();
        List<Map<String,Object>> lists = new ArrayList<>();
        for (Menu menu : menuList) {
            Map<String, Object> map = parseMenuToMap(menu);
            lists.add(map);
        }
        return new Result(true, MessageConst.GET_MENU_SUCCESS,lists);
    }

    /**
     * @Author: 位帅帅
     * @Date: 21:11 2021/1/12
     * @Params: [menu]
     * @RerurnType: java.util.Map<java.lang.String,java.lang.Object>
     * @Description: 将查询结果转化为前端数据
    */
    private Map<String, Object> parseMenuToMap(Menu menu) {
    /*[{
       "path": "2",
       "title": "会员管理",
       "icon":"fa-user-md",
       "children": [{
           "path": "/2-1",
           "title": "会员档案",
           "linkUrl":"member.html",
           "children":[]
       }]
    }]*/
        Map<String, Object> map = new HashMap<>();
        map.put("path",menu.getPath());
        map.put("title",menu.getName());
        map.put("icon",menu.getIcon());
        List<Menu> children = menu.getChildren();
        List<Map<String,Object>> lists = new ArrayList<>();
        if (children != null) {
            for (Menu childMenu : children) {
                Map<String, Object> childmap = new HashMap<>();
                childmap.put("path",childMenu.getPath());
                childmap.put("title",childMenu.getName());
                childmap.put("linkUrl",childMenu.getLinkUrl());
                lists.add(childmap);
            }
        }
        map.put("children",lists);
        return map;
    }

}
